﻿#include"XQFileTableWidget.h"
#include"XQAlgorithm.h"
#include"XQFileThread.h"
#include<QProgressBar>
void XQFileTableWidget::copyFileThreadInit(const QString& name, const QString& newName)
{
    XQFileThread* file = new XQFileThread(name);
    connect(file, &XQFileThread::copyStart, this, &XQFileTableWidget::copyFileThreadStart, Qt::QueuedConnection);
    connect(file, &XQFileThread::copyProgress, this, &XQFileTableWidget::copyFileThreadProgress, Qt::QueuedConnection);
    connect(file, &XQFileThread::copyFinish, this, &XQFileTableWidget::copyFileThreadFinish, Qt::QueuedConnection);
    connect(file, &XQFileThread::copyFinish, file, &XQFileThread::deleteLater, Qt::QueuedConnection);//结束时释放自己
    file->copy(newName);

}
void XQFileTableWidget::copyFileThreadStart(const QString& name, const QString& newName, const size_t fileSize)
{
    // 遍历行
    for (int row = 0; row < rowCount(); row++) {
        // 获取单元格指针
        QTableWidgetItem* item = this->item(row, XQFileTableWidget::Type::name);
        if (item) {
            // 获取单元格数据
            if (newName == item->data(Qt::UserRole).toString())//找到了
            {
                m_items[newName] = item;//存进容器
                break;
            }
        }
    }
    if (m_items.end() == m_items.find(newName))//界面中还没有这个文件
    {
        qInfo() << "界面中没有:" << newName;
        return;
    }
    setProgressBar(m_items[newName]->row(),Type::locality,0, fileSize);
}
void XQFileTableWidget::copyFileThreadProgress(const QString& name, const QString& newName, size_t currentSize, const size_t fileSize)
{
    QTableWidgetItem* item = m_items[newName];//获得他的单元格
    size_t row = item->row();//获得行号
    setProgressBar(m_items[newName]->row(), Type::locality, currentSize, fileSize);
    this->item(row, Type::size)->setText(readableFileSize(currentSize));//设置当前大小
    emit tableFileChange();//通知文件改变了
}
void XQFileTableWidget::copyFileThreadFinish(const QString& name, const QString& newName, const size_t fileSize)
{
    QTableWidgetItem* item = m_items[newName];//获得他的单元格
    size_t row = item->row();//获得行号
    setProgressBar(m_items[newName]->row(), Type::locality, fileSize, fileSize);
    this->item(row, Type::size)->setText(readableFileSize(QFileInfo(newName).size()));//设置当前大小
    this->item(row, Type::size)->setData(Qt::UserRole, QFileInfo(newName).size());
    m_items.remove(name);
    emit tableFileChange();//通知文件改变了
}